<!--
 * @Author: ybf
 * @Date: 2023-02-21 15:31:51
 * @LastEditTime: 2023-02-22 10:43:19
 * @Description: 描述
 * Copyright (c) 2023 by 慧能分享, All Rights Reserved.
-->
<template>
    <div class="wiringDiagram">

        <NuVerifyForm :model="formData" ref="formData" label-width="100px" class="searchForm" @searchForm="searchForm"
            :buttons="fyButtons">
            <NuformItem label="图形名称" prop="dgmName" width="auto">
                <nu-input type="text" v-model="formData.dgmName" size="middle" placeholder="通道名称"></nu-input>
            </NuformItem>
            <div class="btnBox">
                <nu-button type="primary" class="searchButton" @click="searchTable">搜索</nu-button>
                <nu-button class="searchButton" @click="clearParams">清除</nu-button>
            </div>
        </NuVerifyForm>
        <div class="line"></div>
        <div style="height:35px;position: relative;padding: 0 10px;" class="renovateTime">
            <nu-button class="searchButton" @click="addTable" :isDisabled="false">新增</nu-button>
        </div>
        <NuTableList :showFilter="false" :columns="columns" :dataSource="dataSource" :options="options"
            :operates="operates(this)" :pagination="pagination" @handleSizeChange="handleSizeChange"
            @handleChangePage="handleChangePage" @handleCurrentChange="handleCurrentChange">
        </NuTableList>
        <!-- 新增 -->
        <nu-dialog :title="dialogTitle" :visible.sync="dialogShow" width="30%" center :close-on-click-modal="false"
            top="15vh" :modal-append-to-body="false" @close="diaClose">
            <div class="dialogHeaderSearch">
                <NuVerifyForm :model="dialogFormData" ref="dialogFormData" label-width="70px" class="submitForm"
                    @submitForm="diaSubmitForm" :buttons="fyButtons">
                    <NuformItem label="名称" prop="dgmName" width="60%" :rules="[{ required: true, message: '请输入图形名称' }]">
                        <nu-input type="text" v-model="dialogFormData.dgmName" size="middle" :disabled="dialogFormDisabled"
                            placeholder="请输入图形名称"></nu-input>
                    </NuformItem>
                </NuVerifyForm>
                <nu-button class="dialogSearchButton" type="primary" @click="diaClose">取消</nu-button>
                <nu-button class="dialogSearchButton" type="primary" @click="diaSave"
                    v-if="dialogTitle == '编辑'">确定</nu-button>
                <nu-button class="dialogSearchButton" type="primary" @click="diaSave"
                    v-if="dialogTitle == '新建图形'">确定</nu-button>
            </div>
        </nu-dialog>
        <!-- 弹窗 -->
        <nu-dialog title="" :visible.sync="iFrameVisible" width="100%" center :close-on-click-modal="false" top="0"
            :modal-append-to-body="false" @close="iFrameClose" custom-class="iFrame-dialog">
            <iFrame :src="iFrameSrc" iFheight="100%" v-if="iFrameType == 'edit'"></iFrame>
            <div style="width: 100%;height: 100%;" v-html="graphViewSrc" id="svgImgDom" v-else></div>
        </nu-dialog>
    </div>
</template>
    
<script>
import nuCol from "@/components/base/col.vue"
import nutbTitle from "@/components/base/tableTitle.vue"
import NuVerifyForm from "@/components/verify-form"
import NuformItem from "@/components/verify-form/form-item.vue"
import nuInput from "@/components/base/input"
import nuSelect from "@/components/base/select"
import nuButton from "@/components/base/button"
import NuTableList from "@/components/tableList/TableFormList"
import nuDialog from "@/components/base/dialog"
import nuRadio from "@/components/base/radio"
import nuRadioButton from "@/components/base/radio-button"
import axios from 'axios'
import iFrame from "@/components/iFrame"
import { getToken } from "@/utils/auth";
import { getDateTime } from "@/utils/ruoyi";
import downloadSvg from "@/assets/downloadSvg.js";
import _ from 'lodash';
const operates = that => [
    {
        label: '浏览',
        icon: '',
        isShow: row => {
            return true;
        },
        disabled: row => {
            return false;
        },
        method: row => {
            that.openGraphView(row)
        },
    },
    {
        label: '编辑',
        icon: '',
        isShow: row => {
            return true;
        },
        disabled: row => {
            return false;
        },
        method: row => {
            that.openEditGraph(row)
        },
    },
    {
        isShow: row => {
            return false;
        },
    },
    {
        label: '删除',
        icon: '',
        isShow: row => {
            return true;
        },
        disabled: row => {
            return false;
        },
        method: row => {
            that.tbRowdetele(row);
        },
    },
    {
        label: '应用',
        icon: '',
        isShow: row => {
            return row.dgmIfApply == 0 ? true : false;
        },
        disabled: row => {
            return false;
        },
        method: row => {
            that.application(row)
        },
    }
];
export default {
    name: "wiringDiagram",
    components: { iFrame, nuCol, nutbTitle, NuVerifyForm, NuformItem, nuInput, nuSelect, nuButton, NuTableList, nuDialog, nuRadio, nuRadioButton },
    data() {
        return {
            iFrameSrc: '',
            iFrameVisible: false,
            graphViewSrc: '',
            iFrameType: '',
            formData: {
                dgmName: '',
                dgmDrawType: ''
            },
            dialogFormData: {
                dgmName: ''
            },
            operates,
            fyButtons: [],
            currentRow: null,
            pagination: {
                pageSize: 20,
                total: 0,
                currentPage: 1,
            },
            dialogTitle: '',
            dialogShow: false,
            columns: [
                {
                    label: '序号',
                    prop: 'ranking',
                    width: '70px',
                    render: (h, params) => {
                        return h('span', params.index + 1 + (this.pagination.currentPage - 1) * this.pagination.pageSize);
                    },
                },
                {
                    label: '图形名称',
                    prop: 'dgmName',
                    render: (h, params) => {
                        return h('a', {
                            attrs: {
                                href: 'javascript:;',
                            },
                            props: {},
                            style: 'color:#409EFF;',
                            on: {
                                click: val => {
                                    this.openGraphView(params.row)
                                }
                            },
                        }, params.row.dgmName);
                    },
                },
                {
                    label: '版本号',
                    prop: 'dgmVersion',
                },
                {
                    label: '操作人',
                    prop: 'dgmModifierName',
                },
                {
                    label: '是否应用',
                    prop: 'dgmIfApply',
                    render: (h, params) => {
                        // dgmIfApply（是否应用，1：是；0：否）
                        return h('span', params.row.dgmIfApply == 1 ? '是' : '否');
                    },
                },
                {
                    label: '当前编辑人',
                    prop: 'dgmCurrentEditor',
                },
                {
                    label: '修改时间',
                    prop: 'gmtModified',
                    render: (h, params) => {
                        return h('span', getDateTime('', params.row.gmtModified));
                    },
                }
            ],
            dataSource: [],
            options: {
                'default-expand-all': true,
                'element-loading-background': 'rgba(225,239,242)',
                'element-loading-text': '数据正在加载中',
                'row-key': 'pid',
                'header-cell-style': {
                    background: 'rgba(105, 159, 209, 0.7)',
                    color: '#fff',
                    fontWeight: 'bold',
                    fontsize: '16px',
                },
                height: 'calc(100vh - 310px)',
                props: {
                    fixed: 'right'
                }
            },
        };
    },
    computed: {
        dialogFormDisabled() {
            return this.dialogTitle == '详情'
        }
    },
    created() { },
    mounted() {
        //  dgmDrawType (接线图类型)：1：一次接线图形式；0：数据总览图形式
        if (this.$route.query.hasOwnProperty('dgmDrawType')) {
            this.formData.dgmDrawType = this.$route.query.dgmDrawType
        } else {
            this.formData.dgmDrawType = 1
        }
        this.getDrawWiringDiagramInfo();
        window.addEventListener("message", (res) => {
            if (res && Object.keys(res.data).length) {
                if (res.data.type == 'msg') {
                    this.$message({
                        type: res.data.msgType,
                        message: res.data.info
                    });
                }
            }
        })
    },
    beforeDestroy() {

    },
    methods: {
        /**
         * 查询
         */
        searchTable() {
            this.$refs['formData'].searchForm('form');
        },
        /**
         * form组件内置查询事件
         */
        searchForm(val) {
            if (val) {
                this.getDrawWiringDiagramInfo();
            }
        },
        /**
         * 每页条数变化事件
         */
        handleSizeChange(val) {
            this.pagination.currentPage = 1;
            this.pagination.pageSize = val;
            this.getDrawWiringDiagramInfo();
        },
        /**
         * 改变分页触发事件
         */
        handleChangePage(val) {
            this.pagination.currentPage = val;
            this.getDrawWiringDiagramInfo();
        },
        /**
         * 单选
         */
        handleCurrentChange(val) {
            this.currentRow = val
        },
        /**
         * 清除数据
         */
        clearParams() {
            // this.resetForm('formData')
            this.formData.dgmName = ''
        },
        /**
         * 重置表单
         */
        resetForm(formName) {
            this.$refs[formName].resetForm('form');
            for (let k in this[formName]) {
                if (Object.prototype.toString.call(this[formName][k]) == "[object String]") {
                    this[formName][k] = ''
                } else if (Object.prototype.toString.call(this[formName][k]) == "[object Array]") {
                    this[formName][k] = []
                } else if (Object.prototype.toString.call(this[formName][k]) == "[object Number]") {
                    this[formName][k] = ''
                }
            }
        },
        /**
         * 新增
         */
        addTable() {
            this.dialogTitle = '新建图形'
            this.dialogShow = true
            this.dialogFormData.dgmName = ''
            this.iFrameType = 'edit'
            this.$nextTick(() => {
                this.resetForm('dialogFormData')
            })
        },
        /**
         * 查看mxgraph图形
         */
        openGraphView(row) {
            // this.graphViewSrc = downloadSvg
            // this.iFrameVisible = true
            // this.$nextTick(() => {
            //     var panZoomTiger = this.initZoomPan();
            //     panZoomTiger.zoom(0.75);
            //     // $("body").smartMenu([], { name: "body" }); $("body").smartMenu([], { name: "body" });
            // })
            // return false
            this.iFrameType = 'view'
            this.$httpGet(window.api.drawWiringDownload + row.id).then(res => {
                this.graphViewSrc = res
                this.iFrameVisible = true
                this.$nextTick(() => {
                    var panZoomTiger = this.initZoomPan();
                    $("body").smartMenu([], { name: "body" }); $("body").smartMenu([], { name: "body" });
                })
            }).catch(err => {

            });
        },
        // svg缩放拖拽
        initZoomPan() {
            const eventsHandler = {
                haltEventListeners: ['touchstart', 'touchend', 'touchmove', 'touchleave', 'touchcancel'],
                init: function (options) {
                    var instance = options.instance,
                        initialScale = 1,
                        pannedX = 0,
                        pannedY = 0
                    // Init Hammer
                    // Listen only for pointer and touch events
                    this.hammer = Hammer(options.svgElement, {
                        inputClass: Hammer.SUPPORT_POINTER_EVENTS ? Hammer.PointerEventInput : Hammer.TouchInput
                    })
                    // Enable pinch
                    this.hammer.get('pinch').set({ enable: true })
                    // Handle double tap
                    this.hammer.on('doubletap', function (ev) {
                        instance.zoomIn()
                    })
                    // Handle pan
                    this.hammer.on('panstart panmove', function (ev) {
                        // On pan start reset panned variables
                        if (ev.type === 'panstart') {
                            pannedX = 0
                            pannedY = 0
                        }
                        // Pan only the difference
                        instance.panBy({ x: ev.deltaX - pannedX, y: ev.deltaY - pannedY })
                        pannedX = ev.deltaX
                        pannedY = ev.deltaY
                    })
                    // Handle pinch
                    this.hammer.on('pinchstart pinchmove', function (ev) {
                        // On pinch start remember initial zoom
                        if (ev.type === 'pinchstart') {
                            initialScale = instance.getZoom()
                            instance.zoom(initialScale * ev.scale)
                        }
                        instance.zoom(initialScale * ev.scale)
                    })
                    // Prevent moving the page on some devices when panning over SVG
                    options.svgElement.addEventListener('touchmove', function (e) { e.preventDefault(); });
                },
                destroy: function () {
                    this.hammer.destroy()
                }
            }
            const element = document.querySelector('#svgImgDom').firstElementChild;
            element.style.width = '100%'
            element.style.height = '100%'
            var panZoomTiger = svgPanZoom(element, {
                zoomEnabled: true,
                controlIconsEnabled: true,
                dblClickZoomEnabled: false,
                fit: false,
                center: true,
                customEventsHandler: eventsHandler
            });
            let a = document.getElementById('svg-pan-zoom-controls');
            if (a) {
                a.remove();
            }
            return panZoomTiger;
        },
        /**
         * 编辑mxgraph图形
         */
        openEditGraph(row) {
            this.iFrameType = 'edit'
            // this.saveCurrentEditor(row);
            // return false
            this.getCurrentEditor(row)
        },
        /**
         * 表格操作列-删除
         */
        tbRowdetele(row) {
            this.$confirm('确定要删除吗？', '确认删除', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.delChannelSet(row)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        /**
         * 删除表格数据
         */
        delChannelSet(row) {
            this.$httpDel(window.api.drawWiringRemove, row.dgmName).then(res => {
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                this.getDrawWiringDiagramInfo();
            }).catch(err => {
                this.$message({
                    type: 'info',
                    message: err
                });
            });
        },

        /**
         * dialogFormData组件内置提交事件
         */
        diaSubmitForm(val) {
            if (val) {
                if (this.dialogTitle == '编辑') {
                } else if (this.dialogTitle == '新建图形') {
                    if (this.dialogFormData.dgmName.indexOf("_") != -1) {
                        this.$message({
                            type: 'info',
                            message: '请将下划线“_”修改成其他字符'
                        });
                        return;
                    }
                    this.addChannelCondition()
                }
            }
        },
        /**
         * 弹窗-单点新增-保存
         */
        diaSave() {
            this.$refs['dialogFormData'].submitForm('form');
        },
        /**
         * 弹窗-单点新增-关闭
         */
        diaClose() {
            this.dialogShow = false
            this.dialogBatchShow = false
        },
        /**
         * 获取表格数据
         */
        getDrawWiringDiagramInfo() {
            let postData = {
                currentPage: this.pagination.currentPage.toString(),
                pageSize: this.pagination.pageSize.toString(),
                dgmCompanyId: "",
                ...this.formData
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.$httpGet(window.api.drawWiringDiagramInfo, postData).then(res => {
                if (res.code == 200 && res.rows) {
                    this.pagination.total = res.total;
                    this.dataSource = res.rows;

                } else {
                    this.pagination.total = 0;
                    this.dataSource = [];
                }
            }).catch(err => { });
        },
        /**
         * 新建图形
         */
        addChannelCondition() {
            let postData = {
                ...this.dialogFormData,
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.$httpGet(window.api.getList, postData).then(res => {
                if (res.code == 200) {
                    if (res.rows >= 1) {
                        this.$message({
                            type: 'info',
                            message: '已存在相同名称图形，请更换其他名称'
                        });
                        return;
                    }
                    this.iFrameSrc = '/tworulesScene/grapheditor/index.html?name=' + this.dialogFormData.dgmName + '&dgmCompanyId=1&dgmDrawType=' + this.formData.dgmDrawType
                    this.iFrameVisible = true
                    this.diaClose()
                } else {
                }
            }).catch(err => { });
        },
        /**
        * 检测是否有用户在编辑-提示框
        */
        openCurrentEditor(row) {
            this.$confirm('已有用户在修改，是否强制修改。', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.saveCurrentEditor(row);
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        /**
         * 检测是否有用户在编辑
         */
        getCurrentEditor(row) {
            this.saveCurrentEditor(row);
            return false
            let postData = {
                drawId: row.id
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.$httpGet(window.api.getCurrentEditor, postData).then(res => {
                // if (res.successful) {
                if (res.DgmIfEditting == "1") {
                    this.saveCurrentEditor(row);
                } else {
                    this.openCurrentEditor(row)
                }
                // } else {
                // }
            }).catch(err => { });
        },
        /**
         * 打开graph
         * @param {} row 
         */
        saveCurrentEditor(row) {
            let postData = {
                userName: '管理员',
                userId: '1',
                drawId: row.id
            };
            this.$httpGet(window.api.saveCurrentEditor, postData).then(res => {
                this.iFrameSrc = '/tworulesScene/grapheditor/index.html?id=' + row.id + '&editorToken=' + postData.userId + '&username=' + postData.userName + '&dgmCompanyId=1&dgmDrawType=' + this.formData.dgmDrawType
                this.iFrameVisible = true
            }).catch(err => { });
        },
        /**
         * 关闭graph弹窗
         */
        iFrameClose() {
            this.iFrameSrc = ''
            this.iFrameVisible = true
            this.graphViewSrc = ''
            this.getDrawWiringDiagramInfo();
        },
        /**
         * 是否应用
         */
        application(row) {
            let t = {
                1: '此图形展示在一次接线图功能中, 是否继续?',
                0: '此图形展示在数据总览功能中, 是否继续?'
            }
            this.$confirm(t[this.formData.dgmDrawType], '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.setGlobalDrawldByDrawType(row)
            }).catch(() => {});
        },
        /**
         * 应用当前图形
         */
        setGlobalDrawldByDrawType(row) {
            let postData = {
                "drawId": row.id,
                "dgmDrawType": row.dgmDrawType
            }
            this.$httpPost(window.api.setGlobalDrawldByDrawType, postData)
                .then((res) => {
                    if (res.code == 200) {
                        this.$message({
                            message: "成功",
                            type: "success",
                        });
                        this.getDrawWiringDiagramInfo();
                    } else {
                    }
                })
                .catch((err) => { });
        }
    }
};
</script>
    
<style scoped lang="scss">
.wiringDiagram {
    height: 100%;
}

.searchForm {
    // height: calc(100% - 40px);
    display: flex;
    align-items: center;
    position: relative;
}

.submitForm {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    width: 100%;
}

.btnBox {
    display: flex;
    float: right;
    z-index: 10;
    position: absolute;
    top: 15px;
    right: 10px;
}

.dialogHeaderSearch {
    background-color: var(--model-bgc);
    padding: 10px;
    margin-top: 10px;
    display: flex;
    flex-wrap: wrap;
    justify-content: right;
}

::v-deep .el-button--primary {
    background-color: rgba(71, 99, 255, 1);
    border-color: rgba(71, 99, 255, 1);
}

::v-deep .el-dialog:not(.is-fullscreen).iFrame-dialog {
    margin-top: 0vh !important;
    height: calc(100% - 42px);
}

::v-deep .iFrame-dialog .el-dialog__header {
    background: linear-gradient(349deg, rgba(2, 20, 52, 1) 0%, rgba(0, 47, 125, 1) 100%) !important;
}
</style>